package com.jsbs.iam.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.jsbs.iam.common.core.constant.EmployeeConstants;
import com.jsbs.iam.common.core.utils.Json;
import com.jsbs.iam.common.core.utils.StringUtils;
import com.jsbs.iam.common.redis.service.RedisUtils;
import com.jsbs.iam.user.constant.RedisConstants;
import com.jsbs.iam.user.dto.OrgInfoAddDto;
import com.jsbs.iam.user.dto.OrgInfoDeleteDto;
import com.jsbs.iam.user.dto.OrgInfoQueryDto;
import com.jsbs.iam.user.entity.IamAdminRoleOrgInfo;
import com.jsbs.iam.user.entity.IamOrgFramework;
import com.jsbs.iam.user.entity.IamOrgTypeExtendedField;
import com.jsbs.iam.user.mapper.*;
import com.jsbs.iam.user.param.OrgInfoDto;
import com.jsbs.iam.user.param.OrgInfoParam;
import com.jsbs.iam.user.service.OrgInfoService;
import com.jsbs.iam.user.vo.OrgInfoTypeVo;
import com.jsbs.iam.user.vo.OrgInfoVo;
import com.jsbs.iam.user.vo.OrgThreeInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrgInfoServiceImpl implements OrgInfoService {

    private static final Logger logger = LoggerFactory.getLogger(OrgInfoServiceImpl.class);
    @Autowired
    private OrgInfoMapper orgInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private PostInfoMapper postInfoMapper;

    @Autowired
    private PostOrgRelationMapper postOrgRelationMapper;

    @Resource
    private RedissonClient redissonClient;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Value("${_env.name}")
    private String envName;

    @Override
    public void syncOrgInfo(OrgInfoParam orgInfoParam) {
        if (CollectionUtils.isEmpty(orgInfoParam.getOrgInfoList())) {
            return;
        }
        // 新增组织列表
        List<IamOrgFramework> orgList = new ArrayList<>();
        // 更新组织列表
        List<IamOrgFramework> updateList = new ArrayList<>();
        // 组织编码非空
        List<OrgInfoDto> enableOrgList = orgInfoParam.getOrgInfoList().stream().filter(item -> StringUtils.isNotEmpty(item.getOrgCode())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(enableOrgList)) {
            return;
        }
        // 校验通过的组织列表，至校验有效
        enableOrgList.forEach(item -> {
            IamOrgFramework orgInfo = new IamOrgFramework();
            BeanUtils.copyProperties(item, orgInfo);
            // 归属租户
            orgInfo.setCompanyCode(orgInfoParam.getCompanyCode());
            // 组织来源
            orgInfo.setOrgTypeCode(orgInfoParam.getDataSource());
            orgInfo.setOrgType(String.valueOf(EmployeeConstants.employeeMap.get(item.getOrgType())));
            // 判断新增/更新
            if (orgInfoMapper.countByOrgCode(orgInfoParam.getCompanyCode(), orgInfoParam.getDataSource(), item.getOrgCode()) > 0) {
                updateList.add(orgInfo);
            } else {
                // 默认同步
                orgInfo.setSyncFlag(0);
                orgList.add(orgInfo);
            }
        });
        // 批量新增
        if (CollectionUtils.isNotEmpty(orgList)) {
            orgInfoMapper.batchInsert(orgList);
        }
        // 批量更新
        if (CollectionUtils.isNotEmpty(updateList)) {
            orgInfoMapper.batchUpdate(updateList);
        }
    }

    @Override
    public List<OrgThreeInfo> selectOrgTypeInfo(OrgInfoQueryDto orgInfoQueryDto) {
        long s = System.currentTimeMillis();
        log.info("Route=>OrgInfoServiceImpl method=>selectOrgTypeInfo  查询组织树数据==============================>开始{}", s);
        // 是否包含关联岗位
        String postOrgFlag = orgInfoQueryDto.isIncludePost() ? RedisConstants.IAM_ORG_POST : StringUtils.EMPTY;
        // 先从缓存获取组织架构
        List<OrgThreeInfo> compList = RedisUtils.getObjectList(envName + orgInfoQueryDto.getOrgTypeCode() + RedisConstants.IAM_ORG_INFO_LIST + postOrgFlag, OrgThreeInfo.class);
        if (CollectionUtils.isNotEmpty(compList)) {
            logger.info("Route=>OrgInfoServiceImpl method=>selectOrgTypeInfo  Redis  从Redis中获取对应组织类型组织树信息数据，出参：{}", JSON.toJSONString(compList));
            return compList;
        }
        long orgS = System.currentTimeMillis();
        log.info("Route=>OrgInfoServiceImpl method=>selectOrgTypeInfo  查询组织数据,开始{}", orgS);
        // 获取该组织类型下所有组织架构
        List<OrgThreeInfo> orgInfos = orgInfoMapper.selectOrgInfo(orgInfoQueryDto.getOrgTypeCode(), orgInfoQueryDto.getCompanyCode());
        long orgE = System.currentTimeMillis();
        log.info("Route=>OrgInfoServiceImpl method=>selectOrgTypeInfo  查询组织数据,结束{}",orgE);
        log.info("Route=>OrgInfoServiceImpl method=>selectOrgTypeInfo  查询组织数据,耗时{}", (orgE - orgS));
        // 判空
        if (CollectionUtils.isEmpty(orgInfos)) {
            //如果没用一级组织树则返回组织类型数据
            List<OrgThreeInfo> orgTypeInfos = orgInfoMapper.selectOrgTypeInfo(orgInfoQueryDto.getOrgTypeCode(), orgInfoQueryDto.getCompanyCode());
            RedisUtils.setObjectList(envName + orgInfoQueryDto.getOrgTypeCode() + RedisConstants.IAM_ORG_INFO_LIST + postOrgFlag, orgTypeInfos);
            return orgTypeInfos;
        }
        if (orgInfoQueryDto.isIncludePost()) {
            long postS = System.currentTimeMillis();
            log.info("Route=>OrgInfoServiceImpl method=>selectOrgTypeInfo  查询岗位数据,开始{}", postS);
            // 获取该组织类型下所有关联岗位
            orgInfos.addAll(postOrgRelationMapper.queryPostList(orgInfoQueryDto.getOrgTypeCode()));
            long postE = System.currentTimeMillis();
            log.info("Route=>OrgInfoServiceImpl method=>selectOrgTypeInfo  查询岗位数据,结束{}", postE);
            log.info("Route=>OrgInfoServiceImpl method=>selectOrgTypeInfo  查询岗位数据,耗时{}", (postE - postS));
        }
        // 获取所有一级组织层级
        compList = orgInfos.stream().filter(item -> Objects.nonNull(item.getOrgLevel()) && 1 == item.getOrgLevel()).collect(Collectors.toList());
        long recS = System.currentTimeMillis();
        log.info("Route=>OrgInfoServiceImpl method=>selectOrgTypeInfo  递归组织数据,开始{}", recS);
        // 循环封装层级
        recursionData(compList, orgInfos);
        long recE = System.currentTimeMillis();
        log.info("Route=>OrgInfoServiceImpl method=>selectOrgTypeInfo  递归组织数据,结束{}", recE);
        log.info("Route=>OrgInfoServiceImpl method=>selectOrgTypeInfo  递归组织数据,耗时{}", (recE - recS));
        //判断是否为组织管理调用的接口
        if (orgInfoQueryDto.isIncludePost()) {
            // 获取组织类型的数据
            List<OrgThreeInfo> orgThreeInfos = orgInfoMapper.selectOrgTypeInfo(orgInfoQueryDto.getOrgTypeCode(), orgInfoQueryDto.getCompanyCode());
            for (OrgThreeInfo orgThreeInfo : orgThreeInfos) {
                orgThreeInfo.setChildrenOrgs(compList);
            }
            //把组装了组织类型的数据赋值给compList
            compList = orgThreeInfos;
        }

        if (CollectionUtils.isEmpty(compList)) {
            return null;
        }
        // 最新组织架构入缓存
        RedisUtils.setObjectList(envName + orgInfoQueryDto.getOrgTypeCode() + RedisConstants.IAM_ORG_INFO_LIST + postOrgFlag, compList);
        long e = System.currentTimeMillis();
        log.info("Route=>OrgInfoServiceImpl method=>selectOrgTypeInfo  查询组织树数据==============================>结束{}", e);
        log.info("Route=>OrgInfoServiceImpl method=>selectOrgTypeInfo  查询组织树数据==============================>总耗时{}", (e - s));
        return compList;
    }

    @Override
    public List<IamOrgTypeExtendedField> getOrgTypeExtend(String orgTypeCode, String companyCode) {

        return orgInfoMapper.getOrgTypeExtend(orgTypeCode,companyCode);
    }


    @Override
    @Transactional
    public void addOrgInfo(OrgInfoAddDto orgInfoAddDto) {
        List<Map<String, String>> fieldMap = new ArrayList<>();
        //新增组织层级生成编码时加锁,失效时间10分钟
        RLock lock = redissonClient.getLock(RedisConstants.IAM_ORG_CODE_ADD_KEY);
        String orgCode = "";
        try {
            // 5分钟内重试获取锁，10秒后释放
            boolean isLocked = lock.tryLock(5 * 60 * 1000L, 10 * 1000L, TimeUnit.MILLISECONDS);
            // 获取到锁后,进行组织编码自增
            if (!isLocked) {
                log.warn("Route=>OrgInfoServiceImpl method=>addOrgInfo 新增组织层级加锁生成编码失败:{}", Json.toJsonString(orgInfoAddDto));
                throw new Exception();
            }
            //key 拼接规则 组织类型_当前层级编码
            String key = "";
            if (StringUtils.isNotEmpty(orgInfoAddDto.getOrgTypeCode())) {
                if (StringUtils.isEmpty(orgInfoAddDto.getOrgCode())) {
                    //添加第一层组织(不包含组织类型)
                    key = orgInfoAddDto.getOrgTypeCode();
                } else {
                    //添加第一层以下组织
                    key = orgInfoAddDto.getOrgTypeCode() + "_" + orgInfoAddDto.getOrgCode();
                }
            }
            // 加锁成功后获取当前缓存值
            String value = RedisUtils.get(envName + key);
            // 若为空则从数据库取当前层级的下一层最大编码,并加入到缓存中
            if (StringUtils.isEmpty(value)) {
                //设置层级 用于查询子级
                orgInfoAddDto.setOrgLevel(orgInfoAddDto.getOrgLevel() + 1);
                String subOrgCode = "";
                //根据不同的层级查询组织下级编码
                if (orgInfoAddDto.getOrgLevel() == 1) {
                    //添加一级组织  通过组织类型编码查询一级组织编码
                    subOrgCode = orgInfoMapper.getSubOrgCodeByOrgCode(orgInfoAddDto);
                }else {
                    //添加一级以后的组织  通过组织父级编码查询下级组织编码
                    subOrgCode = orgInfoMapper.getSubOrgCodeBySuperCode(orgInfoAddDto);
                }
                if (StringUtils.isEmpty(subOrgCode)) {
                    //初始化下级编码
                    if (orgInfoAddDto.getOrgLevel() == 1) {
                        //子级OrgLevel等于1 为组织类型添加第一层组织 code 组织类型编码01  zzlx00000101
                        orgCode = orgInfoAddDto.getOrgTypeCode() + "01";
                    } else if (orgInfoAddDto.getOrgLevel() == 2) {
                        //子级OrgLevel等于2 为第一层组织添加第二层组织 code 第一层组织编码01  zzlx0000010101
                        orgCode = orgInfoAddDto.getOrgCode() + "01";
                    } else {
                        //子级OrgLevel大于等于3  zzlx0000010101001
                        orgCode = orgInfoAddDto.getOrgCode() + "001";
                    }
                } else {
                    String num = subOrgCode.replace(orgInfoAddDto.getOrgCode(), "");
                    int numInt = Integer.parseInt(num);
                    numInt++;
                    //控制补0的位数
                    int place = 2;
                    if (orgInfoAddDto.getOrgLevel() >= 3) {//大于2的层级为3位数
                        place = 3;
                    }
                    orgCode = orgInfoAddDto.getOrgCode() + String.format("%0" + place + "d", numInt);//后缀不够place长，前面补充0
                }
            } else {
                // 当前缓存获取成功
                String num = "";
                if (orgInfoAddDto.getOrgLevel() >= 2) {//大于2的层级001
                    num = value.substring(value.length() - 3);
                } else {
                    num = value.substring(value.length() - 2);
                }
                //String num = value.replace(orgInfoAddDto.getOrgCode(), "");
                int numInt = Integer.parseInt(num);
                numInt++;
                int place = 2;
                if (orgInfoAddDto.getOrgLevel() >= 2) {//大于2的层级为3位数
                    place = 3;
                }
                String prefix = (StringUtils.isEmpty(orgInfoAddDto.getOrgCode())) ? orgInfoAddDto.getOrgTypeCode() : orgInfoAddDto.getOrgCode();

                orgCode = prefix + String.format("%0" + place + "d", numInt);//后缀不够place长，前面补充0
                //设置层级
                orgInfoAddDto.setOrgLevel(orgInfoAddDto.getOrgLevel() + 1);
            }

            // 将最新值更新到缓存中,过期时间24小时
            RedisUtils.set(envName + key, orgCode, 24 * 60 * 60 * 1000L, TimeUnit.MILLISECONDS);
            log.info("新增组织层级生成编码redis===>key: {}", key);
            log.info("新增组织层级生成编码redis===>value: {}", orgCode);
        } catch (Exception e) {
            log.error("Route=>OrgInfoServiceImpl method=>addOrgInfo 新增组织层级加锁生成编码失败:{}, e:{}", Json.toJsonString(orgInfoAddDto), e);
            e.printStackTrace();
            throw new RuntimeException("新增组织层级生成编码异常");
        } finally {
            // 手动解锁
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
        //设置父级编码
        orgInfoAddDto.setOrgParentCode(StringUtils.isEmpty(orgInfoAddDto.getOrgCode()) ? "0" : orgInfoAddDto.getOrgCode());
        //设置组织编码
        orgInfoAddDto.setOrgCode(orgCode);
        //新增组织数据
        orgInfoMapper.addOrgInfo(orgInfoAddDto);
        //新增扩展字段数据
        if (CollectionUtils.isNotEmpty(orgInfoAddDto.getExtendData())) {
            for (Map<String, String> extendDatum : orgInfoAddDto.getExtendData()) {
                if (MapUtils.isNotEmpty(extendDatum)) {
                    Set<String> keys = extendDatum.keySet();
                    for (String fieldId : keys) {
                        String data = extendDatum.get(fieldId);
                        //拼接字段
                        Map<String, String> dataMap = new HashMap<>();
                        dataMap.put("fieldId", fieldId);//字段id
                        dataMap.put("data", data);//字段对应的值
                        dataMap.put("orgCode", orgCode);//组织编码
                        dataMap.put("companyCode", orgInfoAddDto.getCompanyCode());
                        dataMap.put("createPerson", orgInfoAddDto.getCreatePerson());
                        fieldMap.add(dataMap);
                    }
                }
            }
            //保存扩展字段数据
            orgInfoMapper.insetExtendData(fieldMap);
        }

        //更新Redis缓存
        this.updateRedisKey(orgInfoAddDto.getOrgTypeCode());
    }

    @Override
    @Transactional
    public void deleteOrgInfo(OrgInfoDeleteDto deleteDto) {

        //获取所有下级组织编码
        List<String> codeData = this.recursionCodeData(deleteDto.getOrgCode(),deleteDto.getCompanyCode());
        codeData.add(deleteDto.getOrgCode());
        deleteDto.setCodeData(codeData);

        //通过组织编码逻辑删除组织数据
        orgInfoMapper.deleteOrgData(deleteDto);
        //通过组织编码删除组织扩展数据
        orgInfoMapper.deleteExtendData(deleteDto);
         //更新Redis缓存
        this.updateRedisKey(deleteDto.getOrgTypeCode());
    }

    @Override
    public OrgInfoVo selectOrgInfo(OrgInfoAddDto orgInfoAddDto) {
        OrgInfoVo orgInfoVo = new OrgInfoVo();
        Integer orgLevel = orgInfoAddDto.getOrgLevel();
        //通过层级判断 组织类型 组织 岗位
        if (orgLevel == null) {//岗位
            //根据岗位编码查询岗位数据
            orgInfoVo = postInfoMapper.selectPostInfo(orgInfoAddDto);
        } else if (orgLevel == 0) {//组织类型
            //根据组织类型编码获取组织类型数据
            orgInfoVo = orgInfoMapper.selectOrgTypeData(orgInfoAddDto);
        } else {//组织
            //根据组织编码查询组织主数据
            IamOrgFramework orgMainData = orgInfoMapper.selectOrgMainData(orgInfoAddDto);
            //根据组织编码查询组织扩展字段数据
            List<Map<String, String>> fieldMap = orgInfoMapper.selectOrgExtendedData(orgInfoAddDto);
            if (ObjectUtils.isNotEmpty(orgMainData)) {
                //组装vo数据
                orgInfoVo.setOrgCode(orgMainData.getOrgCode());
                orgInfoVo.setOrgName(orgMainData.getOrgName());
                orgInfoVo.setOrgIndex(orgMainData.getOrgIndex());
                orgInfoVo.setOrgStatus(orgMainData.getOrgStatus());
                if (CollectionUtils.isNotEmpty(fieldMap)) {
                    orgInfoVo.setExtendData(fieldMap);
                }
            }
        }

        //根据组织类型和组织编码查询用户数量
        int userCount = userInfoMapper.getUserCount(orgInfoAddDto.getOrgTypeCode(), orgInfoAddDto.getOrgCode(),orgInfoAddDto.getCompanyCode());
        //设置用户数量
        orgInfoVo.setUserCount(userCount);
        return orgInfoVo;
    }

    @Override
    @Transactional
    public void updateOrgInfo(OrgInfoAddDto orgInfoAddDto) {
        List<Map<String, String>> fieldMap = new ArrayList<>();
        //更新组织主数据
        orgInfoMapper.updateOrgMainData(orgInfoAddDto);

        List<Map<String, String>> extendData = orgInfoAddDto.getExtendData();
        if (CollectionUtils.isNotEmpty(extendData)) {
            for (Map<String, String> map : extendData) {
                if (MapUtils.isNotEmpty(map)) {
                    Set<String> keySet = map.keySet();
                    for (String fieldId : keySet) {
                        String data = map.get(fieldId);
                        Map<String, String> dataMap = new HashMap<>();
                        dataMap.put("fieldId", fieldId);
                        dataMap.put("data", data);
                        dataMap.put("orgCode", orgInfoAddDto.getOrgCode());
                        dataMap.put("companyCode", orgInfoAddDto.getCompanyCode());
                        dataMap.put("createPerson", orgInfoAddDto.getCreatePerson());
                        fieldMap.add(dataMap);
                    }
                }
            }
            //更新组织扩展数据
            orgInfoMapper.updateOrgExtendedData(fieldMap);
        }
        //更新Redis缓存
        this.updateRedisKey(orgInfoAddDto.getOrgTypeCode());
    }

    @Override
    public int verifyLevel(String orgCode, String companyCode) {
        return orgInfoMapper.verifyLevel(orgCode, companyCode);
    }

    @Override
    public int getUserCount(String orgTypeCode, String orgCode, String companyCode) {
        return userInfoMapper.getUserCount(orgTypeCode, orgCode, companyCode);
    }

    @Override
    public void moveOrg(OrgInfoAddDto orgInfoAddDto) {
        //修改组织层级之间的关系
        orgInfoMapper.updateOrgLevel(orgInfoAddDto);
        //更新Redis缓存
        this.updateRedisKey(orgInfoAddDto.getOrgTypeCode());
    }

    /**
     *删除Redis中缓存
     * @param orgTypeCode
     */
    private void updateRedisKey(String orgTypeCode) {
        RedisUtils.del(envName + orgTypeCode + RedisConstants.IAM_ORG_INFO_LIST + RedisConstants.IAM_ORG_POST);
    }

    /**
     * 通过编码获取下级所有组织编码
     *
     * @param code
     * @param companyCode
     * @return
     */
    private List<String> recursionCodeData(String code, String companyCode) {
        List<String> recursionList = new ArrayList<String>();
        if (StringUtils.isNotEmpty(code)) {
            List<String> subCode2 = orgInfoMapper.selectSubOrgCode(code,companyCode);
            if (CollectionUtils.isNotEmpty(subCode2)) {
                for (String s : subCode2) {
                    if (StringUtils.isNotEmpty(s)) {
                        List<String> codeData = this.recursionCodeData(s, companyCode);
                        recursionList.addAll(codeData);
                    }
                }
            }
            recursionList.addAll(subCode2);
        }
        return recursionList;
    }

    /**
     * 功能描述：获取下级数据
     * @param orgThreeInfos
     * @param orgInfoList
     * @return
     */
    private void recursionData(List<OrgThreeInfo> orgThreeInfos, List<OrgThreeInfo> orgInfoList) {
        if (CollectionUtils.isEmpty(orgInfoList)) {
            return;
        }
        // 循环封装
        orgThreeInfos.forEach(item -> {
            if (Objects.nonNull(item.getIsPost()) && item.getIsPost() == 1) {
                return;
            }
            List<OrgThreeInfo> children = new ArrayList<>();
            Iterator<OrgThreeInfo> iterator = orgInfoList.iterator();
            while (iterator.hasNext()) {
                OrgThreeInfo orgThreeInfo = iterator.next();
                // 获取当前层级的子级
                if (StringUtils.isNotEmpty(orgThreeInfo.getParentCode()) && orgThreeInfo.getParentCode().equals(item.getCode())) {
                    children.add(orgThreeInfo);
                    // 将当前匹配到的对象从集合中移除
                    iterator.remove();
                }
            }
            // 获取所有子级
            if (CollectionUtils.isNotEmpty(children)) {
                // 排序
                children.sort(Comparator.comparing(OrgThreeInfo::getOrgIndex));
                // 递归封装子级的子级
                recursionData(children, orgInfoList);
                // 当前层级的所有子级
                item.setChildrenOrgs(children);
            }
        });
    }

    @Override
    public List<OrgInfoTypeVo> queryByCode(List<String> orgcodeList, String orgTypeCode){
        return orgInfoMapper.queryByCode(orgcodeList, orgTypeCode);
    }

    @Override
    public List<OrgThreeInfo> getOrgThreeAllInfo(String companyCode) {
        //List<OrgThreeInfo> compList =new ArrayList<OrgThreeInfo>();
        // 先从缓存获取组织架构所有数据
        List<OrgThreeInfo> compList = RedisUtils.getObjectList(envName + RedisConstants.IAM_ORG_THREE_ALL, OrgThreeInfo.class);
        if (CollectionUtils.isNotEmpty(compList)) {
            logger.info("Route=>OrgInfoServiceImpl method=>getOrgThreeAllInfo  Redis  从Redis中获取所有组织树数据，出参：{}", JSON.toJSONString(compList));
            return compList;
        }
        // 获取所有组织架构数据
        List<OrgThreeInfo> orgInfos = orgInfoMapper.selectOrgAllInfo(companyCode);
        // 获取所有关联岗位数据
        orgInfos.addAll(postOrgRelationMapper.queryPostAllList(companyCode));
        // 判空
        if (CollectionUtils.isEmpty(orgInfos)) {
            return null;
        }
        // 获取所有一级组织层级
        compList = orgInfos.stream().filter(item -> Objects.nonNull(item.getOrgLevel()) && 1 == item.getOrgLevel()).collect(Collectors.toList());
        // 循环封装层级
        recursionData(compList, orgInfos);
        // 获取组织类型的数据
        List<OrgThreeInfo> orgThreeInfos = orgInfoMapper.selectOrgTypeAllInfo(companyCode);
        //重新组装数据
        for (OrgThreeInfo orgThreeInfo : orgThreeInfos) {
            List<OrgThreeInfo> children = new ArrayList<>();
            for (OrgThreeInfo threeInfo : compList) {
                //获取组织类型下的一级组织
                if (orgThreeInfo.getCode().equals(threeInfo.getOrgTypeCode())) {
                    children.add(threeInfo);
                }
                //排序
                children.sort(Comparator.comparing(OrgThreeInfo::getOrgIndex));
            }
            orgThreeInfo.setChildrenOrgs(children);
        }
        compList = orgThreeInfos;
        if (CollectionUtils.isEmpty(compList)) {
            return null;
        }
        // 最新组织架构入缓存 ,12小时有效
        RedisUtils.setObjectList(envName + RedisConstants.IAM_ORG_THREE_ALL, compList,12, TimeUnit.HOURS);
        return compList;
    }

    @Override
    public IamOrgTypeExtendedField getExtendInfo(String fieldId, String companyCode) {
        return orgInfoMapper.getExtendInfo(fieldId, companyCode);
    }

    @Override
    public int verifyIsSole(String fieldId, String fieldData, String companyCode) {
        return orgInfoMapper.verifyIsSole(fieldId, fieldData, companyCode);
    }

    @Override
    public String verifyFieldData(String fieldId, String orgCode, String companyCode) {
        return orgInfoMapper.verifyFieldData(fieldId, orgCode, companyCode);
    }

    @Override
    public List<OrgThreeInfo> selectOrgTypeInfoRestrict(OrgInfoQueryDto orgInfoQueryDto) {
        //获取所有组织树数据
        List<OrgThreeInfo> orgThreeInfos = this.selectOrgTypeInfo(orgInfoQueryDto);
        List<IamAdminRoleOrgInfo> adminRoleOrgInfo = adminRoleMapper.getAdminRoleOrgInfo(orgInfoQueryDto.getAdminRoleCode(), orgInfoQueryDto.getCompanyCode());
        List<String> orgRole = new ArrayList<String>();
        if (CollectionUtils.isNotEmpty(adminRoleOrgInfo)) {
            if (adminRoleOrgInfo.get(0).getType() == 1) {
                //取出所有组织编码
                for (IamAdminRoleOrgInfo iamAdminRoleOrgInfo : adminRoleOrgInfo) {
                    orgRole.add(iamAdminRoleOrgInfo.getOrgCode());
                }
            } else {
                String orgTypeCode = adminRoleOrgInfo.get(0).getOrgTypeCode();
                //通过组织类型查询组织编码
                orgRole = orgInfoMapper.getOrgCodesByOrgType(orgTypeCode, orgInfoQueryDto.getCompanyCode());
                //把组织类型编码塞入到权限中
                orgRole.add(orgTypeCode);
            }
        }
        if (CollectionUtils.isNotEmpty(orgThreeInfos) && CollectionUtils.isNotEmpty(orgRole)) {
            //递归处理权限数据
            this.recursionDealData(orgThreeInfos, orgRole);
            return orgThreeInfos;
        } else {
            return null;
        }
    }

    /**
     * 递归处理权限数据
     * @param orgThreeInfos  对应组织类型组织树数据
     * @param orgPermissions   对应有权限的数据
     */
    public void recursionDealData(List<OrgThreeInfo> orgThreeInfos, List<String> orgPermissions) {
        if (CollectionUtils.isNotEmpty(orgThreeInfos) && CollectionUtils.isNotEmpty(orgPermissions)) {
            for (OrgThreeInfo orgThreeInfo : orgThreeInfos) {
                for (String orgPermission : orgPermissions) {
                    if (orgPermission.equals(orgThreeInfo.getCode())) {
                        //所有有权限的都打上标记 0:有权限 1:没有权限
                        orgThreeInfo.setDisabled(0);
                    } else if (orgThreeInfo.getDisabled() == null) {
                        orgThreeInfo.setDisabled(1);
                    }
                    if (CollectionUtils.isNotEmpty(orgThreeInfo.getChildrenOrgs())) {
                        this.recursionDealData(orgThreeInfo.getChildrenOrgs(), orgPermissions);
                    }
                }
            }
        }
    }

}
